<template>
  <a-layout>
    <a-layout-header>
      <a-typography-title>个人中心</a-typography-title>
    </a-layout-header>
    <a-layout>
      <a-layout-sider>
        <!--        <a-avatar-->
        <!--          :size="128"-->
        <!--          v-if="user.userAvatar == '' || user.userAvatar == null"-->
        <!--          shape="circle"-->
        <!--          style="background-color: #1890ff"-->
        <!--        >-->
        <!--          {{ user.userName.substr(0, 1) }}-->
        <!--        </a-avatar>-->
        <!--        <a-avatar v-else :size="128" :src="user.userAvatar"></a-avatar>-->
        <a-upload
          v-model:file-list="fileList"
          name="avatar"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          :before-upload="beforeUpload"
          :customRequest="customRequest"
        >
          <a-tooltip placement="bottom" v-if="user.userAvatar" >
            <template #title>
              <span>点击更换头像</span>
            </template>
<!--            <img style="height: 102px; width: 102px;"  :src="user.userAvatar" alt="avatar" />-->
            <a-avatar shape="square" :size="103" :src="user.userAvatar"></a-avatar>
          </a-tooltip>
          <div v-else>
            <loading-outlined v-if="loading"></loading-outlined>
            <plus-outlined v-else></plus-outlined>
            <div class="ant-upload-text">Upload</div>
          </div>
        </a-upload>

      </a-layout-sider>
      <a-layout-content>
        <a-list-item>
          <template #extra>
            <span style="display: flex; align-items: flex-end; height: 40px">
              <a-space>
                <span>加入于:</span>
                {{ formatDateTime(user.createTime) }}
              </a-space>
            </span>
          </template>
          <a-list-item-meta class="content">
            <template #title class="item-title">
              <a-space>
                <strong>{{ user.userName }}</strong>
                <a-tag color="#55acee">{{ user.userRole }}</a-tag>
              </a-space>
            </template>

            <template #description>
              <div style="margin-top: 30px"></div>
              <a-typography-paragraph
                v-if="user.userProfile != ''"
                v-model:content="user.userProfile"
                copyable
              />
              <a-typography-paragraph v-else>
                编辑个签,展示我的独特态度。
                <EditOutlined />
              </a-typography-paragraph>
              <!--              <div>-->
              <!--                <PlusOutlined />-->
              <!--                你从事什么职业？-->
              <!--              </div>-->
              <!--              <div>-->
              <!--                <PlusOutlined />-->
              <!--                你的武器库有哪些武(yu)器(yan)？-->
              <!--              </div>-->
            </template>
          </a-list-item-meta>
        </a-list-item>
      </a-layout-content>
    </a-layout>
  </a-layout>

  <a-divider style="height: 2px; background-color: #5a6253" />
</template>

<script setup lang="ts">
import myAxios from "@/plugins/myAxios";
import { EditOutlined, PlusOutlined } from "@ant-design/icons-vue";
import { onBeforeMount, ref } from "vue";

interface UserType {
  id: "";
  userName: "";
  userAvatar: "";
  userProfile: "";
  userRole: "";
  createTime: "";
  updateTime: "";
}

let user = ref({
  id: "123",
  userName: "123",
  userAvatar: "",
  userProfile: "",
  userRole: "",
  createTime: "",
  updateTime: "",
});
const getLogin = () => {
  myAxios.get("/user/get/login").then((res: any) => {
    user.value = res;
    console.log(res);
  });
};
onBeforeMount(() => {
  getLogin();
});

function formatDateTime(date: string): string {
  const datetime = new Date(date);
  const year = datetime.getFullYear();
  const month = String(datetime.getMonth() + 1).padStart(2, "0");
  const day = String(datetime.getDate()).padStart(2, "0");
  const hour = String(datetime.getHours()).padStart(2, "0");
  const minute = String(datetime.getMinutes()).padStart(2, "0");
  const format = `${year}-${month}-${day} ${hour}:${minute}`;
  return format;
}

// upload

import type { UploadChangeParam, UploadProps } from 'ant-design-vue';
import { message } from 'ant-design-vue';
import router from "@/router";
const beforeUpload = (file: UploadProps["fileList"][number]) => {
  const isJpgOrPng =
    file.type === 'image/jpeg' ||
    file.type === 'image/png' ||
    file.type === 'image/gif' ||
    file.type === 'image/webp' ||
    file.type === 'image/jpg'

  if (!isJpgOrPng) {
    message.error("请上传正确的图片格式");
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("Image must smaller than 2MB!");
  }
  return isJpgOrPng && isLt2M;
};

function getBase64(img: Blob, callback: (base64Url: string) => void) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result as string));
  reader.readAsDataURL(img);
}

const fileList = ref([]);
const loading = ref<boolean>(false);
const imageUrl = ref<string>("");

const handleChange = (info: UploadChangeParam) => {
  console.log(info);

  if (info.file.status === "uploading") {
    loading.value = true;
    return;
  }
  if (info.file.status === "done") {
    // Get this url from response in real world.
    getBase64(info.file.originFileObj, (base64Url: string) => {
      imageUrl.value = base64Url;
      loading.value = false;
    });
  }
  if (info.file.status === "error") {
    loading.value = false;
    message.error("upload error");
  }
};


const customRequest = ({ file }: any) => {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('biz', "user_avatar");
  myAxios.post("/file/upload",formData).then((res: any) => {
    if(res){
      user.value.userAvatar = res
      console.log(res);
      message.success(res)
      update()
    }else {
      message.error("图片上传失败");
    }
  });
}
const update = () => {
  myAxios.post("/user/update/my", user.value).then((res: any) => {
    if (res) {
      message.success("头像修改成功");
      router.go(0);
    }
  });
}


</script>

<style scoped lang="less">
.ant-layout-header {
  padding: 0;
  margin: 0;
  background: #f0f2f5;
}

.ant-layout-sider {
  display: flex;
  justify-content: center;
  background: #f0f2f5;
}

.ant-layout-content {
  //color: #000000;
  background: #f0f2f5;
}

// update
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
